var ctx=window.daijia.ctx;
var address=window.daijia.address;
var ismainCompany=window.daijia.mainCompany;
var map3=null;
var driving3=null;
var distance=null;
var timeStr=null;
var orderType=null;//订单类型 id
var finalServiceType="tangzu";//默认为立即用车服务
var firstCarTypeId=null;
var number=0;
var numberMoney=0;
var startzhuan = new Array();
var endzhuan = new Array();
var yugu_money=0;
var initcarnum=0;
var finalDistance=0.0;
var finalTime=0;
var oldselected=null;
var carTypeId_couponIds=null;
var isfirstload=true;//地图第一次加载
var city = null;
var changed = true;
function initialize3(){
	var myGeo = new BMap.Geocoder();
	
	myGeo.getPoint(address, function(point){
		if (point) {
			map3 = new BMap.Map("allmap3");  
			map3.centerAndZoom(point, 13);
			map3.enableScrollWheelZoom();
			
			driving3 = new BMap.DrivingRoute(map3, {   
				policy : BMAP_DRIVING_POLICY_LEAST_DISTANCE,
				onSearchComplete: function(results){
					if (driving3.getStatus() == BMAP_STATUS_SUCCESS){
						var plan = results.getPlan(0);// 获取第一条方案  
						distance=plan.getDistance();
						timeStr=plan.getDuration();
						$("#priceText").parent().css("display","block");
						$("#priceText").text("预计时间:"+timeStr+",预计路程:"+distance);
						
						getCarTypesMoney();
						
					}else{
						getStartMoney();
					}
				},
				renderOptions: {    //显示到地图上
					map: map3,    
					autoViewport: true 
				}  
			});
			//右键菜单
			var contextMenu = new BMap.ContextMenu();    
			var txtMenuItem = [{
				text:'设为预约地',
				callback:function(p){
					map3.clearOverlays();				   		
					var memberMarker = new BMap.Marker(p);  // 创建标注
					map3.addOverlay(memberMarker);
					
					var gc = new BMap.Geocoder();
					gc.getLocation(p, function(rs){
						var addComp = rs.addressComponents;
						$("#startAddress3").val(addComp.street);
						$("#startLng3").val(p.lng);
						$("#startLat3").val(p.lat);
						startzhuan[0]=p.lng;
						startzhuan[1]=p.lat;
						if(startzhuan.length!=0 && endzhuan.length!=0){
							var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
							var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
							map3.centerAndZoom(startPoint, 10); 
							driving3.search(startPoint, endPoint);
						}else{
							getStartMoney();
						}
						$("#startAddressDetail3").val("");
						if(rs.surroundingPois[0]!=null && rs.surroundingPois[0].title.trim()!=null && rs.surroundingPois[0].title.trim()!=""){
							$("#startAddressDetail3").val(rs.surroundingPois[0].title);
						}
					});         
				}
			},{
				text:'设为目的地',
				callback:function(p){
					map3.clearOverlays();
					
					var memberMarker = new BMap.Marker(p);  // 创建标注
					map3.addOverlay(memberMarker);
					
					var gc = new BMap.Geocoder();
					gc.getLocation(p, function(rs){
						var addComp = rs.addressComponents;
						$("#endAddress3").val(addComp.street);
						$("#endLng3").val(p.lng);
						$("#endLat3").val(p.lat);
						endzhuan[0]=p.lng;
						endzhuan[1]=p.lat;
						if(startzhuan.length!=0 && endzhuan.length!=0){
							var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
							var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
							map3.centerAndZoom(startPoint, 10); 
							driving3.search(startPoint, endPoint);
						}else{
							getStartMoney();
						}
						$("#endAddressDetail3").val("");
						if(rs.surroundingPois[0]!=null && rs.surroundingPois[0].title.trim()!=null && rs.surroundingPois[0].title.trim()!=""){
							$("#endAddressDetail3").val(rs.surroundingPois[0].title);
						}
					});         
				}
			}];
			
			for(var i=0; i < txtMenuItem.length; i++){
				contextMenu.addItem(new BMap.MenuItem(txtMenuItem[i].text,txtMenuItem[i].callback,100));
				if(i==1 || i==3) {
					contextMenu.addSeparator();
				}
			}
			map3.addContextMenu(contextMenu); 
			map3.addEventListener('tilesloaded',function(){
				if(isfirstload){
					isfirstload=false;
					if($("#passengerPhone3").val()){
						$("#passengerPhone3").change();
					}
				}
			});
		}else{
			$.scojs_message("地区"+address+"位置不准确,请重新编辑地区", $.scojs_message.TYPE_ERROR);
		}
	});
}
function getStartMoney(){
	// $("#zhuanCreate").removeAttr("disabled");
	// $("#priceText").parent().css("display","block");
	$("#priceText").text("预计时间:0分钟,预计路程:0公里");
	var carTypes=$(".carType_div");
	var moneylist = new Array();
	var text="";
	var finalCompanyId=null;
	if(ismainCompany=="true"){
		finalCompanyId=$("#companyId3").val();
	}
	for(var i=0;i<carTypes.length;i++){
		var c=carTypes[i];
		var carType_id=$(c).attr("carTypeId");
		var n=$(c).children('input');
		var s=$(c).parent().next();
		var money=$(s).children('div').children('input');
		var num=$(n).val();//该车型的车辆数量 
		if(carType_id!=null && num>0){//车辆数量不为0的车型才预算费用
			$.ajax({
	             type: "POST",
	             async : false,
	             url: ctx+"/zhuanche/getPrice",
	             data: {carTypeId:carType_id,companyId:finalCompanyId,time:"0分钟",mileage:"0公里",passengerPhone:$("#passengerPhone3").val(),serviceType:finalServiceType},
	             dataType: "json",
	             success: function(data){
					yugu_money=data.money;
					finalTime=data.travelTime;
					finalDistance=data.mileage;
			    	var travelTime="0";
			    	if(data.travelTime != null){
			    		travelTime=data.travelTime;
			    	} else {
			    		$.scojs_message("无法预算,请检查收费标准是否已删除", $.scojs_message.TYPE_ERROR);
			    	}
			    	var mileage="0";
			    	if(data.mileage){
			    		mileage=data.mileage;
			    	}
			    	$("#priceText").parent().css("display","block");
			    	$("#priceText").text("预计时间:"+travelTime+"分钟,预计路程:"+mileage+"公里");
			    	
			    	if(text!=null && text!=""){
			    		text+=",";
			    	}
			    	text+="{'carTypeId':"+carType_id+",'number':"+num+",'areaId':"+data.areaId+",'budgetPay':"+data.money+",'startPrice':"+data.startPrice+",'mileagePrice':"+data.mileagePrice+",'travelTimePrice':"+data.travelTimePrice+"}";
		    	 }
	         });
			moneylist.push(yugu_money);
		}else{
			moneylist.push(0);
		}
	}
	$("#carTypes").val(text);
	
	for(var i=0;i<carTypes.length;i++){//每个类型预算费用并且乘以车辆数量
		var c=carTypes[i];
		var n=$(c).children('input');
		var s=$(c).parent().next();
		var money=$(s).children('div').children('input');
		var m=moneylist[i];
		var num=$(n).val();//该车型的车辆数量 
		var v=m*num;
		if(v){
			$(money).val(v.toFixed(1));
		}
		if(i==carTypes.length-1){
			sumCarNumber();
		}
	}
}
//预算费用
function getCarTypesMoney(){
//	$("#zhuanCreate").removeAttr("disabled");
	var carTypes=$(".carType_div");
	var moneylist = new Array();
	var text="";
	var finalCompanyId=null;
	if(ismainCompany=="true"){
		finalCompanyId=$("#companyId3").val();
	}
	for(var i=0;i<carTypes.length;i++){
		var c=carTypes[i];
		var carType_id=$(c).attr("carTypeId");
		var n=$(c).children('input');
		var s=$(c).parent().next();
		var money=$(s).children('div').children('input');
		var num=$(n).val();//该车型的车辆数量 
		if(carType_id!=null && num>0){//车辆数量不为0的车型才预算费用
			$.ajax({
	             type: "POST",
	             async : false,
	             url: ctx+"/zhuanche/getPrice",
	             data: {carTypeId:carType_id,companyId:finalCompanyId,time:timeStr,mileage:distance,passengerPhone:$("#passengerPhone3").val(),serviceType:finalServiceType},
	             dataType: "json",
	             success: function(data){
					yugu_money=data.money;
					finalTime=data.travelTime;
					finalDistance=data.mileage;
					var travelTime="0";
			    	if(data.travelTime != null){
			    		travelTime=data.travelTime;
			    	} else {
		    			$.scojs_message("无法预算,请检查收费标准是否已删除", $.scojs_message.TYPE_ERROR);
			    	}
			    	var mileage="0";
			    	if(data.mileage){
			    		mileage=data.mileage;
			    	}
			    	$("#priceText").parent().css("display","block");
			    	$("#priceText").text("预计时间:"+travelTime+"分钟,预计路程:"+mileage+"公里");
			    	
			    	if(text!=null && text!=""){
			    		text+=",";
			    	}
			    	text+="{'carTypeId':"+carType_id+",'number':"+num+",'areaId':"+data.areaId+",'budgetPay':"+data.money+",'startPrice':"+data.startPrice+",'mileagePrice':"+data.mileagePrice+",'travelTimePrice':"+data.travelTimePrice+"}";
		    	 }
	         });
			moneylist.push(yugu_money);
		}else{
			moneylist.push(0);
		}
	}
	$("#carTypes").val(text);
	
	for(var i=0;i<carTypes.length;i++){//每个类型预算费用并且乘以车辆数量
		var c=carTypes[i];
		var n=$(c).children('input');
		var s=$(c).parent().next();
		var money=$(s).children('div').children('input');
		var m=moneylist[i];
		var num=$(n).val();//该车型的车辆数量 
		var v=m*num;
		if(v){
			$(money).val(v.toFixed(1));
		}
		if(i==carTypes.length-1){
			sumCarNumber();
		}
	}
	
};
function clickCoupon(d){
	oldselected=$(d).find("option:selected");
};
function changeCoupon(d){
	var couponId=$(d).find("option:selected").val();
	var select_coupon=$(".select_coupon").children("option");
	var allselect=$(".select_coupon");
	var c=$(d).parent().parent().parent().prev();
	var car_div=$(c).children('div');
	var c_div=$(car_div).find('div');
	var span_c=$(d).next().find('span');
	var money_div=$(car_div).next();
	var car_num=$(car_div).find('input').val();//车辆数量
	var money_input=$(money_div).find('input');//原金额
	if(couponId){
		$(allselect).each(function(index,element){
			var s=allselect[index];
			if(couponId!=$(s).find("option:selected").val()){
				var oneselect=$(s).children("option");
				$(oneselect).each(function(x,element){
					var one=oneselect[x];
					if(couponId==$(one).val()){
						s.options.remove(x);//删除元素
					}
				});
			}
		});
		
		var selected=$(d).find("option:selected");
		var type=$(selected).attr("type");//0打折 1抵扣
		var discount=$(selected).attr("discount");//8 八折
		var money=$(selected).attr("money");//抵扣金额
		var span_coupon=$(span_c).text();
		var money_old=0;
		if(Number($(money_input).val())>0){
			money_old=Number($(money_input).val());
			if(Number(span_coupon)>0){
				money_old=Number(money_old)+Number(span_coupon);
			}
		}
		
		var newMoney=0;
		var c_money=0;
		if(car_num>1){
			if(type==0){//打折
				c_money=money_old/car_num*(10-discount)/10;
				newMoney=(money_old-money_old/car_num)+(money_old/car_num*discount/10);
			}else{//抵扣
				c_money=money;
				newMoney=(money_old-money_old/car_num)+money_old/car_num-money;
				if(newMoney<0){
					newMoney=0;
					c_money=0;
				}
			}
		}else if(car_num==1){
			if(type==0){//打折
				c_money=money_old*(10-discount)/10;
				newMoney=money_old*discount/10;
			}else{//抵扣
				c_money=money;
				newMoney=money_old-money;
				if(newMoney<0){
					newMoney=0;
					c_money=0;
				}
			}
		}
		$(money_input).val(newMoney.toFixed(1));//优惠后的钱
		$(span_c).text(Number(c_money).toFixed(1));//优惠的钱
		if(carTypeId_couponIds!=null && carTypeId_couponIds!=""){
			carTypeId_couponIds+=","+$(c_div).attr("carTypeId")+"-"+couponId;
		}else{
			carTypeId_couponIds=$(c_div).attr("carTypeId")+"-"+couponId;
		}
		sumCarNumber();
	}else{
		var span_coupon=$(span_c).text();
		var newMoney=0;
		if(Number($(money_input).val())>0){
			newMoney=Number($(money_input).val());
			if(Number(span_coupon)>0){
				newMoney=Number(newMoney)+Number(span_coupon);
			}
		}
		if(newMoney>=0 && car_num>0){
			$(money_input).val(newMoney.toFixed(1));
		}
		$(span_c).text(0);
		$(allselect).each(function(index,element){
			var s=allselect[index];
			var canappend=true;
			var oneselect=$(s).children("option");
			$(oneselect).each(function(x,element){
				var one=oneselect[x];
				if($(oldselected).val()==$(one).val()){
					canappend=false;
				}
			});
			if(canappend){
				$(s).append("<option  value='"+$(oldselected).val()+"' type='"+$(oldselected).attr('type')+"' discount='"+$(oldselected).attr('discount')+"' money='"+$(oldselected).attr('money')+"'>"+$(oldselected).text()+"</option>");
			}
		});
		if(carTypeId_couponIds!=null && carTypeId_couponIds!=""){
			carTypeId_couponIds+=","+$(c_div).attr("carTypeId")+"-"+"0";
		}
		oldselected=null;
		sumCarNumber();
	}
};
function sumCarNumber(){
	var carNumbers=$(".carNumber");
	number=0;
	numberMoney=0;
	
	for(var i=0;i<carNumbers.length;i++){
		var n=carNumbers[i].value;
		number+=Number(n);
	}
	var yuguMoney=$(".yuguMoney");
	for(var i=0;i<yuguMoney.length;i++){
		var m=yuguMoney[i].value;
		numberMoney+=Number(m);
	}
	var couponMoney_span=$(".couponMoney_span");
	var couponMoney=0;
	for(var i=0;i<couponMoney_span.length;i++){
		var s=couponMoney_span[i];
		var m=$(s).text();
		couponMoney+=Number(m);
	}
	var couponMoneyStr="";
	if(couponMoney>0 && number!=0){
		couponMoneyStr="，优惠券已抵扣<span style='color:red;font-size:20px;'>"+couponMoney.toFixed(1)+"</span>元"
	}
	$("#sumCar_sumMoney").html("");
	if(number==0){
		$("#sumCar_sumMoney").css("display","none");
	}else{
		$("#sumCar_sumMoney").css("display","block");
		$("#sumCar_sumMoney").html("共<span style='color:red;font-size:20px;'>"+number+"</span>辆车，共约<span style='color:red;font-size:20px;'>"+numberMoney.toFixed(1)+"</span>元"+couponMoneyStr);
	}
};
function setCarTypes(companyId,coupons){
	$("#carTypes_div").empty();
	$.get(ctx+'/zhuanche/queryCarTypes',{'companyId':companyId},function(carTypeData){
		if(carTypeData.success){
			$(carTypeData.carTypes).each(function(index,element){
				var id=carTypeData.carTypes[index].id;
				if(index==0){
					firstCarTypeId=id;
				}
				var typeName=carTypeData.carTypes[index].typeName;
				var text="<div class='form-group'><div class='col-sm-6'>";
            	text+="<div class='input-group carType_div' carTypeId='"+id+"'>";
            	text+="<span  class='input-group-addon'>"+typeName+"</span>";
            	text+="<input class='form-control carNumber' type='number'";
            	if(index==0){
            		text+="value='1'";
            	}
            	text+=" min='0'/><span class='input-group-addon'>辆</span></div></div>";
            	text+="<div class='col-sm-6'><div class='input-group'><span  class='input-group-addon'>车型预计</span><input class='form-control yuguMoney' name='yuguMoney' type='text'/><span class='input-group-addon'>元</span>";
            	text+="</div></div></div>";
            	if(coupons!=null && coupons.length>0){
	            	text+="<div class='form-group' id='zhuan_couponInput'>";
	            	text+="<div class='col-sm-12'>";
	            	text+="<div class='input-group'>";
	            	text+="<div class='input-group-addon'>优惠券</div>";
	            	text+="<select class='form-control select_coupon' onclick='clickCoupon(this)' onchange='changeCoupon(this)'>";
	            	text+="<option value=''>"+"请选择优惠券"+"</option>";
	            	for(var i=0;i<coupons.length;i++){
	            		text+= "<option value='"+coupons[i].id+"' type='"+coupons[i].couponRule.type+"' discount='"+coupons[i].couponRule.discount+"' money='"+coupons[i].couponRule.money+"'>"+coupons[i].couponRule.title+"</option>";
					}
	            	text+="</select>";
	            	text+="<span class='input-group-btn'><button class='btn btn-default' type='button'>优惠券已抵扣<span class='couponMoney_span'>0</span>元</button></span>";
	            	text+="</div></div></div>";
            	}
            	$("#carTypes_div").append(text);
			 });
			//重新预算
			if(startzhuan.length!=0 && endzhuan.length!=0){
				getCarTypesMoney();
			}else if(startzhuan.length!=0){
				getStartMoney();
			}
		//	$("#zhuanCreate").removeAttr("disabled");
		}else{
			$("#sumCar_sumMoney").html("");
		//	$("#zhuanCreate").attr("disabled","disabled");
		}
	},'json');
};
$(document).ready(function(){
	initialize3();
	var carNumbers=$(".carNumber");
	if(carNumbers.length>0){
		var first=carNumbers[0];
		$(first).val(1);
	}
	$("#zhuanClick").click(function(){
		initialize3();
		$("#serviceTypes li").removeClass("active");
		$(".firstService").addClass('active');
		finalServiceType="tangzu";
	});
	$(".serviceType").click(function(){
		$("#serviceTypes li").removeClass("active");
		$(this).parent().addClass('active');
		finalServiceType=$(this).parent().attr("serviceType");
		var hadyusuan = true;
		if(finalServiceType=="jieji" || finalServiceType=="songji"){
			hadyusuan = false;
			city = $('#companyId3').find("option:selected").attr("data-city");
			map3.centerAndZoom(city, 10);
			var local = new BMap.LocalSearch(map3, {
				renderOptions:{map: map3}
			});
			local.search("机场");
			local.setSearchCompleteCallback(function(){
				if(local.getResults().wr.length>0){
			    	if(finalServiceType=="jieji"){
						$("#startAddress3").val(local.getResults().wr[0].title);
						$("#startLng3").val(local.getResults().wr[0].point.lng);
						$("#startLat3").val(local.getResults().wr[0].point.lat);
					}else{
						$("#endAddress3").val(local.getResults().wr[0].title);
						$("#endLng3").val(local.getResults().wr[0].point.lng);
						$("#endLat3").val(local.getResults().wr[0].point.lat);
					}
				}	
			});
			local.setInfoHtmlSetCallback(function(poi,html){
				if(finalServiceType=="jieji"){
					$("#startAddress3").val(poi.marker.getTitle());
					$("#startLng3").val(poi.marker.point.lng);
					$("#startLat3").val(poi.marker.point.lat);
					startzhuan[0]=poi.marker.point.lng;
					startzhuan[1]=poi.marker.point.lat;
					if(startzhuan.length!=0 && endzhuan.length!=0){
						var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
						var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
						map3.centerAndZoom(startPoint, 10); 
						driving3.search(startPoint, endPoint);
					}else{
						getStartMoney();
					}
				}else{
					$("#endAddress3").val(poi.marker.getTitle());
					$("#endLng3").val(poi.marker.point.lng);
					$("#endLat3").val(poi.marker.point.lat);
					endzhuan[0]=poi.marker.point.lng;
					endzhuan[1]=poi.marker.point.lat;
					if(startzhuan.length!=0 && endzhuan.length!=0){
						var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
						var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
						map3.centerAndZoom(startPoint, 10); 
						driving3.search(startPoint, endPoint);
					}else{
						getStartMoney();
					}
				}
			});
			
			$("#flightNo_div").css("display","block");
		}else{
			$("#flightNo_div").css("display","none");
		}
		if(finalServiceType=="jiezhan" || finalServiceType=="songzhan"){
			hadyusuan = false;
			city = $('#companyId3').find("option:selected").attr("data-city");
			map3.clearOverlays();
			map3.centerAndZoom(city, 13);
			map3.enableScrollWheelZoom();
			var local = new BMap.LocalSearch(map3, {
				renderOptions:{map: map3}
			});
			local.search("火车站");
			local.setSearchCompleteCallback(function(){
				if(local.getResults().wr.length>0){
					if(finalServiceType=="jiezhan"){
						$("#startAddress3").val(local.getResults().wr[0].title);
						$("#startLng3").val(local.getResults().wr[0].point.lng);
						$("#startLat3").val(local.getResults().wr[0].point.lat);
					}else{
						$("#endAddress3").val(local.getResults().wr[0].title);
						$("#endLng3").val(local.getResults().wr[0].point.lng);
						$("#endLat3").val(local.getResults().wr[0].point.lat);
					}
				}	
			});
			local.setInfoHtmlSetCallback(function(poi,html){
				
				if(finalServiceType=="jiezhan"){
					$("#startAddress3").val(poi.marker.getTitle());
					$("#startLng3").val(poi.marker.point.lng);
					$("#startLat3").val(poi.marker.point.lat);
					startzhuan[0]=poi.marker.point.lng;
					startzhuan[1]=poi.marker.point.lat;
					if(startzhuan.length!=0 && endzhuan.length!=0){
						var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
						var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
						map3.centerAndZoom(startPoint, 10); 
						driving3.search(startPoint, endPoint);
					}else{
						getStartMoney();
					}
				}else{
					$("#endAddress3").val(poi.marker.getTitle());
					$("#endLng3").val(poi.marker.point.lng);
					$("#endLat3").val(poi.marker.point.lat);
					endzhuan[0]=poi.marker.point.lng;
					endzhuan[1]=poi.marker.point.lat;
					if(startzhuan.length!=0 && endzhuan.length!=0){
						var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
						var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
						map3.centerAndZoom(startPoint, 10); 
						driving3.search(startPoint, endPoint);
					}else{
						getStartMoney();
					}
				}
			});
			
			$("#trainNo_div").css("display","block");
		}else{
			$("#trainNo_div").css("display","none");
		}
		if(hadyusuan){
			if(startzhuan.length!=0 && endzhuan.length!=0){
				getCarTypesMoney();
			}else if(startzhuan.length!=0){
				getStartMoney();
			}
		}
		
	});
	
	$(document).on("mousedown",".carNumber",function(){
		changed = true;
		if($(this).val()!="" && $(this).val()!=0){
			initcarnum=$(this).val();
		}else{
			initcarnum=0;
		}
	});
	
	$(document).on("change",".carNumber",function(){
		var num=$(this).val();
		var s=$(this).parent().parent().next();
		var money=$(s).children('div').children('input');
		firstCarTypeId=$(this).parent().attr("carTypeId");
		var m=$(money).val();
		if(num!=0 && m!=0 && initcarnum!=0){
			var initmoney=m/initcarnum;
			var x=initmoney*num;
			$(money).val(x.toFixed(1));
		}else{
			$(money).val(0);
		}
		if(initcarnum==0 || num==0){
			if(startzhuan.length!=0 && endzhuan.length!=0){
				getCarTypesMoney();
			}else if(startzhuan.length!=0){
				getStartMoney();
			}
		}
		sumCarNumber();
		initcarnum=0;
		changed = false;
	});
	
	$(document).on("click",".carNumber",function(){
		if(changed){
			var num=$(this).val();
			var s=$(this).parent().parent().next();
			var money=$(s).children('div').children('input');
			firstCarTypeId=$(this).parent().attr("carTypeId");
			var m=$(money).val();
			if(num!=0 && m!=0 && initcarnum!=0){
				var initmoney=m/initcarnum;
				var x=initmoney*num;
				$(money).val(x.toFixed(1));
			}else{
				$(money).val(0);
			}
			if(initcarnum==0 || num==0){
				if(startzhuan.length!=0 && endzhuan.length!=0){
					getCarTypesMoney();
				}else if(startzhuan.length!=0){
					getStartMoney();
				}
				var allselect=$(".select_coupon");
				$(allselect).each(function(index,element){
					var s=allselect[index];
					var canappend=true;
					var oneselect=$(s).children("option");
					$(oneselect).each(function(x,element){
						var one=oneselect[x];
						if($(oldselected).val()==$(one).val()){
							canappend=false;
						}
					});
					if(canappend){
						$(s).append("<option  value='"+$(oldselected).val()+"' type='"+$(oldselected).attr('type')+"' discount='"+$(oldselected).attr('discount')+"' money='"+$(oldselected).attr('money')+"'>"+$(oldselected).text()+"</option>");
					}
				});
			}
			sumCarNumber();
			initcarnum=0;
			changed = false;
		}
	});
	
	
	$(document).on("change",".yuguMoney",function(){
		sumCarNumber();
	});
	$("#serverTime3").val(new Date().Format("yyyy-MM-dd hh:mm"));
	
	//公司修改后对应的车辆类型也修改
	$("#companyId3").change(function(){
    	var companyId=$("#companyId3").val();
    	$("#carTypeId").html("");
    	$.get(ctx+'/zhuanche/queryCarTypes',{'companyId':companyId},function(data){
    		if(data.success){
    			$("#carTypes_div").html("");
    			
    			$.get(ctx+'/member/findByPhone',{'phone':$("#passengerPhone3").val(),'couponType':'zhuanche'},function(result){
	    			$(data.carTypes).each(function(index,element){
						var id=data.carTypes[index].id;
						if(index==0){
							firstCarTypeId=id;
						}
						var typeName=data.carTypes[index].typeName;
		            	var text="<div class='form-group'><div class='col-sm-6'>";
		            	text+="<div class='input-group carType_div' carTypeId='"+id+"'>";
		            	text+="<span  class='input-group-addon'>"+typeName+"</span>";
		            	text+="<input class='form-control carNumber' type='number'";
		            	if(index==0){
		            		text+="value='1'";
		            	}
		            	text+=" min='0'/><span class='input-group-addon'>辆</span></div></div>";
		            	text+="<div class='col-sm-6'><div class='input-group'><span  class='input-group-addon'>车型预计</span><input class='form-control yuguMoney' name='yuguMoney' type='text'/><span class='input-group-addon'>元</span>";
		            	text+="</div></div></div>";
		            	if(result.coupons!=null && result.coupons.length>0){//优惠券
			            	text+="<div class='form-group'>";
			            	text+="<div class='col-sm-12'>";
			            	text+="<div class='input-group'>";
			            	text+="<div class='input-group-addon'>优惠券</div>";
			            	text+="<select class='form-control select_coupon' onclick='clickCoupon(this)' onchange='changeCoupon(this)'>";
			            	text+="<option value=''>"+"请选择优惠券"+"</option>";
			            	for(var i=0;i<result.coupons.length;i++){
								text+= "<option value='"+result.coupons[i].id+"' type='"+result.coupons[i].couponRule.type+"' discount='"+result.coupons[i].couponRule.discount+"' money='"+result.coupons[i].couponRule.money+"'>"+result.coupons[i].couponRule.title+"</option>";
							}
			            	text+="</select>";
			            	text+="<span class='input-group-btn'><button class='btn btn-default' type='button'>优惠券已抵扣<span class='couponMoney_span'>0</span>元</button></span>";
			            	text+="</div></div></div>";
		            	}
		            	$("#carTypes_div").append(text);
					 });
    			});
    		//	$("#zhuanCreate").removeAttr("disabled");
    		}else{
    			firstCarTypeId=null;
    			$("#carTypes_div").empty();
    			$("#carTypes_div").append("<div class='form-group'><div class='col-sm-12'><span style='color:red;font-size:20px;'>该公司没有开通车型,请开通专车车型后再下单</span></div></div>");
    		//	$("#zhuanCreate").attr("disabled","disabled");
    			$("#sumCar_sumMoney").html("");
    		}
    	},'json');
	});
	$("#passengerPhone3").change(function(){
		$.get(ctx+'/member/findByPhone',{'phone':$(this).val(),'couponType':'zhuanche'},function(data){
			if(data.passenger!=null){
				$("#passengerId3").val(data.passenger.id);
				$("#passengerName3").val(data.passenger.name);
				$("#passengerPhone3").val(data.passenger.phone);
				$("#clientVirtual3").text(data.passenger.drawMoney+data.passenger.nodrawMoney+"元");
				if(data.passenger.inBlackList){
					$("#membertype3").html("黑名单");
				}else{
					$("#membertype3").html(data.passenger.typeStr);
				}
				$("#companyId3 option").each(function(index,element){
					if($(element).attr("value")==data.passenger.companyId){
						$(element).attr("selected","selected");
						return false;
					}
				});
				var companyId=data.passenger.companyId;
				setCarTypes(companyId,data.coupons);
			}else{
				$("#passengerId3").val();
				$("#passengerName3").val("先生/女士");
				$("#membertype3").html("新客户");
				$("#clientVirtual3").html("0元");
				setCarTypes(data.companyId,null);
			}
		});
		
	});
	
	$("#zhuanCreate").click(function(){
	//	$("#zhuanCreate").attr("disabled","disabled");
		var employId=$("input[name='checkDriver']:checked").val();
		if(employId){
			$("#employId3").val(employId);
		}
		if($("#passengerPhone3").val()==''){
			$.scojs_message("请填写客户电话", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#passengerName3").val()==''){
			$.scojs_message("请填写客户姓名", $.scojs_message.TYPE_ERROR);
			return;
		} else if ($("#passengerName3").val().length>6){
			$.scojs_message("客户姓名过长", $.scojs_message.TYPE_ERROR);
			return;
		}
		if(ismainCompany=="true" && !$("#companyId3").val()){
			$.scojs_message("请选择公司", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#startAddress3").val()==''){
			$.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
			return;
		}
		if($("#startLat3").val()==null || $("#startLng3").val()==null){
			$.scojs_message("请先定位你的预约地", $.scojs_message.TYPE_ERROR);
			return false;
		}
		if($("#serverTime3").val()==null || $("#serverTime3").val()==''){
			$.scojs_message("请选择预约时间", $.scojs_message.TYPE_ERROR);
			return false;
		}
		
		var flightNo=$("#flightNo").val();
		if(flightNo!=null && flightNo!=""){
			if(!(/^[A-z,0-9]{4,10}$/.test(flightNo))){
				$.scojs_message("航班号格式错误,请输入字母和数字", $.scojs_message.TYPE_ERROR);
				return false;
			}
		}
		var trainNo=$("#trainNo").val();
		if(trainNo!=null && trainNo!=""){
			if(!(/^[GTKDZLCSgtkdzlcs]{0,1}[0-9]{1,5}$/.test(trainNo))){
				$.scojs_message("车次号格式错误,请输入字母和数字", $.scojs_message.TYPE_ERROR);
				return false;
			}
		}

        var makeprice=$("#makePrice").val();
        var ismakepriced=$("#isMakePrice").val();
        if(ismakepriced==1){
            if(!(/^\d+(\.\d{1,2})?$/.test(makeprice))){
                $.scojs_message("请输入正确的订单定价", $.scojs_message.TYPE_ERROR);
                return false;
            }
        }
		
		if(ismainCompany=="true"){
				$.ajax({
		             type: "POST",
		             url: ctx+"/zhuanche/create",
		             data: {
		            	 passengerId:$("#passengerId3").val(),
		            	 passengerName:$("#passengerName3").val(),
		            	 passengerPhone:$("#passengerPhone3").val(),
		            	 companyId:$("#companyId3").val(),
		            	 companyName:$('#companyId3').find("option:selected").text(),
		            	 serviceType:finalServiceType,
		            	 carTypes:$("#carTypes").val(),
		            	 startAddress:$("#startAddress3").val(),
		            	 startAddressDetail:$("#startAddressDetail3").val(),
		            	 startLat:$("#startLat3").val(),
						 startLng:$("#startLng3").val(),
						 endAddress:$("#endAddress3").val(),
						 endAddressDetail:$("#endAddressDetail3").val(),
						 endLat:$("#endLat3").val(),
						 endLng:$("#endLng3").val(),
		            	 serverTime:$("#serverTime3").val(),
		            	 memo:$("#zhuan_memo").val(),
		            	 flightNo:$("#flightNo").val(),
		            	 trainNo:$("#trainNo").val(),
		            	 makePrice:makeprice,
                         isMakePrice:ismakepriced,
		            	 travelTime:finalTime,
						 mileage:finalDistance,
						 couponIds:carTypeId_couponIds
		             },	
		             dataType: "json",
		             success: function(data){ 
		            	 if(data.success){
		            		 $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
		            		 issubmit=true;
		            		 window.close();
		            		 window.opener.location.reload(true);
		            		 
		            	 }else{
		            		 $.scojs_message("下单失败", $.scojs_message.TYPE_ERROR);
		            	 }
		             }
		         });
			}else{
				$.ajax({
		             type: "POST",
		             url: ctx+"/zhuanche/create",
		             data: {
		            	 passengerId:$("#passengerId3").val(),
		            	 passengerName:$("#passengerName3").val(),
		            	 passengerPhone:$("#passengerPhone3").val(),
		            	 serviceType:finalServiceType,
		            	 carTypes:$("#carTypes").val(),
		            	 startAddress:$("#startAddress3").val(),
		            	 startAddressDetail:$("#startAddressDetail3").val(),
		            	 startLat:$("#startLat3").val(),
						 startLng:$("#startLng3").val(),
						 endAddress:$("#endAddress3").val(),
						 endAddressDetail:$("#endAddressDetail3").val(),
						 endLat:$("#endLat3").val(),
						 endLng:$("#endLng3").val(),
		            	 serverTime:$("#serverTime3").val(),
		            	 memo:$("#zhuan_memo").val(),
		            	 flightNo:$("#flightNo").val(),
		            	 trainNo:$("#trainNo").val(),
		            	 makePrice:makeprice,
                         isMakePrice:ismakepriced,
		            	 travelTime:finalTime,
						 mileage:finalDistance,
						 couponIds:carTypeId_couponIds
		             },	
		             dataType: "json",
		             success: function(data){ 
		            	 if(data.success){
		            		 $.scojs_message("下单成功", $.scojs_message.TYPE_OK);
		            		 issubmit=true;
		            		 window.close();
		            		 window.opener.location.reload(true);
		            	 }else{
		            		 $.scojs_message("下单失败", $.scojs_message.TYPE_ERROR);
		            	 }
		             }
		         });
			}
	});
	
	$("#btn-startAddress3").click(function(){
		if($("#startAddress3").val()==''){
			$.scojs_message("请填写预约地", $.scojs_message.TYPE_ERROR);
		}else{
			map3.clearOverlays();
			var local = new BMap.LocalSearch(map3, {
				renderOptions:{map: map3, autoViewport:true}
			});
			local.search($("#startAddress3").val());
			
			local.setInfoHtmlSetCallback(function(poi,html){
				$("#startLng3").val(poi.marker.point.lng);
				$("#startLat3").val(poi.marker.point.lat);
				startzhuan[0]=poi.marker.point.lng;
				startzhuan[1]=poi.marker.point.lat;
				var title = poi.marker.getTitle();
				var markers = map3.getOverlays();
				for(var i=0;i<markers.length;i++){
					markers[i].show();
				}
				if(endzhuan.length!=0){
					var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
					var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
					driving3.search(startPoint, endPoint);
					poi.marker.hide(); 
				}else if(startzhuan.length!=0){
					var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
					map3.centerAndZoom(startPoint, 10); 
					driving3.search(startPoint, null);
				}
			});
		}
	});
	
	$("#btn-endAddress3").click(function(){
		if($("#endAddress3").val()==''){
			$.scojs_message("请填写目的地再定位", $.scojs_message.TYPE_ERROR);
			if(startzhuan.length!=0){
	        	var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
				var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
				driving3.search(startPoint, endPoint);
			    poi.marker.hide(); 
	        }
		}else{
			map3.clearOverlays();
			var local = new BMap.LocalSearch(map3, {
	    	  renderOptions:{map: map3, autoViewport:true}
	    	});
		    local.search($("#endAddress3").val());
		    local.setInfoHtmlSetCallback(function(poi,html){
	    	   $("#endLng3").val(poi.marker.point.lng);
		       $("#endLat3").val(poi.marker.point.lat);
		        endzhuan[0]=poi.marker.point.lng;
		        endzhuan[1]=poi.marker.point.lat;
		        var markers = map3.getOverlays();
				for(var i=0;i<markers.length;i++){
					markers[i].show();
				}
		        if(startzhuan.length!=0){
		        	var startPoint=new BMap.Point(startzhuan[0], startzhuan[1]);
					var endPoint=new BMap.Point(endzhuan[0],endzhuan[1]);
					driving3.search(startPoint, endPoint);
				    poi.marker.hide(); 
		        }
		    });
		}
	});
	
	$("#startAddress3").AutoComplete({
		data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
		itemHeight: 24,
		max:1,
		width: "auto",
		async: true,
		listStyle: "custom",
		emphasis: false,
		matchHandler: function(keyword, data){
			return true;
		},
		createItemHandler: function(index, data){
			if(data.address.length>14){
				return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
			}
			return "<span title='"+data.address+"'>"+data.address+"</span>";
		},
		afterSelectedHandler: function(data){
			var address = (data.address).split(" ");
			$("#startAddress3").val(address[0]);
			$("#startAddressDetail3").val(address[1]);
			
			$("#startLat3").val(data.latitude);
			$("#startLng3").val(data.longitude);
			startzhuan[0]=data.longitude;
			startzhuan[1]=data.latitude;
			if($("#endAddress3").val()!=""){
				var startPoint=new BMap.Point(parseFloat($("#startLng3").val()),parseFloat($("#startLat3").val()));
				var endPoint=new BMap.Point(parseFloat($("#endLng3").val()),parseFloat($("#endLat3").val()));
				map3.centerAndZoom(startPoint, 10); 
				driving3.search(startPoint, endPoint);	
			}else if(startzhuan.length!=0){
				var startPoint=new BMap.Point(parseFloat($("#startLng3").val()),parseFloat($("#startLat3").val()));
				map3.centerAndZoom(startPoint, 10); 
				driving3.search(startPoint, null);	
			}
			
			var p = new BMap.Point(data.longitude,data.latitude);
		    var marker = new BMap.Marker(p); 
		    map3.addOverlay(marker);
		}
	}).AutoComplete('show');
	
	$("#endAddress3").AutoComplete({
		data: ctx+"/order/getHistoryInputedPlace",
		ajaxDataType: "json",
		itemHeight: 24,
		max:1,
		width: "auto",
		async: true,
		listStyle: "custom",
		emphasis: false,
		matchHandler: function(keyword, data){
			return true;
		},
		createItemHandler: function(index, data){
			if(data.address.length>14){
				return "<span title='"+data.address+"'>"+data.address.substring(0,14)+"</span>";
			}
			return "<span title='"+data.address+"'>"+data.address+"</span>";
		},
		afterSelectedHandler: function(data){
			var address = (data.address).split(" ");
			$("#endAddress3").val(address[0]);
			$("#endAddressDetail3").val(address[1]);
			$("#endLat3").val(data.latitude);
			$("#endLng3").val(data.longitude);
			endzhuan[0]=data.longitude;
			endzhuan[1]=data.latitude;
			if($("#startAddress3").val()!=""){
				var startPoint=new BMap.Point(parseFloat($("#startLng3").val()),parseFloat($("#startLat3").val()));
				var endPoint=new BMap.Point(parseFloat($("#endLng3").val()),parseFloat($("#endLat3").val()));
				map3.centerAndZoom(startPoint, 10); 
				driving3.search(startPoint, endPoint);	
			}
			var p = new BMap.Point(data.longitude,data.latitude);
		    var marker = new BMap.Marker(p); 
		    map3.addOverlay(marker);
		}
	}).AutoComplete('show');
	
});

Date.prototype.Format = function(fmt) 
{ 
  var o = { 
    "M+" : this.getMonth()+1,                 //月份 
    "d+" : this.getDate(),                    //日 
    "h+" : this.getHours(),                   //小时 
    "m+" : this.getMinutes(),                 //分 
    "s+" : this.getSeconds(),                 //秒 
    "q+" : Math.floor((this.getMonth()+3)/3), //季度 
    "S"  : this.getMilliseconds()             //毫秒 
  }; 
  if(/(y+)/.test(fmt)) 
    fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
  for(var k in o) 
    if(new RegExp("("+ k +")").test(fmt)) 
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
  return fmt; 
}
